import React, { useEffect, useState, useCallback } from 'react';
import { default as useFetchList } from '@/hooks/getList';
import {
  Card,
  Table,
  TableColumnProps,
  Button,
  Message,
  Switch,
  Popconfirm,
} from '@arco-design/web-react';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
import AddOrEditForm from '@/pages/manuals/educationManuals/components/addOrEditBox';
import {
  manualsTypeOpt,
  OperateType,
} from '@/pages/manuals/educationManuals/common';
import { useHistory } from 'react-router-dom';
import {
  getHelpManualPage,
  addHelpManual,
  editHelpManual,
  getChildHelpManuals,
  deleteHelpManual,
  enableHelpManual,
} from '@/api/manuals';

dayjs.extend(utc);

function Manuals() {
  const history = useHistory();
  const { data, pagination, loading, getData } = useFetchList(
    getHelpManualPage,
    {}
  );

  const onChangeTable = (pagination) => {
    const { current, pageSize } = pagination;
    const obj = {
      PageIndex: current,
      PageSize: pageSize,
    };
    getData(obj);
  };

  const [modalVisible, setModalVisible] = useState(false);
  const [editData, setEditData] = useState(null);
  const [formShowType, setFormShowType] = useState(OperateType.Add);
  const [currentOperateId, setCurrentOperateId] = useState('');

  const handleChangeVisible = useCallback((visible) => {
    setModalVisible(visible);
  }, []);

  // 关闭新增/编辑弹窗
  const onCancel = useCallback(() => {
    setEditData({});
  }, []);

  const handleAddOrEdit = async (type: OperateType, row = {}) => {
    setFormShowType(type);
    if (type === OperateType.Add) {
      setEditData({});
      setModalVisible(true);
      setCurrentOperateId('');
    } else {
      const res: any = await getChildHelpManuals({ ID: (row as any).ID });
      if (res.StatusCode === 200) {
        setEditData(res.Result);
        setCurrentOperateId(res.Result.ID);
        setModalVisible(true);
      } else {
        Message.error(res.Message);
      }

      setEditData({});
    }
  };

  // 新增/编辑提交
  const onConfirm = useCallback(
    async (reqData: any) => {
      reqData.ID = currentOperateId;
      let res;
      if (formShowType === OperateType.Add) {
        res = await addHelpManual(reqData);
      } else {
        res = await editHelpManual(reqData);
      }

      if (res.StatusCode === 200) {
        handleChangeVisible(false);
        Message.success(res.Message);
        getData();
      } else {
        Message.error(res.Message);
      }
    },
    [formShowType, currentOperateId]
  );

  const deleteRow = async (row) => {
    const res: any = await deleteHelpManual({ ID: row.ID });
    if (res.StatusCode === 200) {
      Message.success(res.Message);
      getData();
    } else {
      Message.error(res.Message);
    }
  };

  const handleEnableManual = async (row) => {
    const res: any = await enableHelpManual({
      ID: row.ID,
    });
    if (res.StatusCode === 200) {
      Message.success(res.Message);
      getData();
    } else {
      Message.error(res.Message);
    }
  };

  const columns: TableColumnProps[] = [
    {
      title: '序号',
      align: 'center',
      render: (col, item: any, index: number) => index + 1,
    },
    {
      title: '分类ID',
      dataIndex: 'ID',
      align: 'center',
      width: 250,
    },
    {
      title: '类型',
      dataIndex: 'Type',
      align: 'center',
      render: (col, record: any) => {
        return manualsTypeOpt.find((opt) => opt.value === col)?.label;
      },
    },
    {
      title: '一级分类名称',
      dataIndex: 'Name',
      align: 'center',
    },
    {
      title: '修改人',
      dataIndex: 'ModifiedName',
      align: 'center',
    },
    {
      title: '修改时间',
      dataIndex: 'ModifiedOn',
      align: 'center',
    },

    {
      title: '操作',
      dataIndex: 'op',
      align: 'center',
      fixed: 'right',
      width: 350,
      render: (_, record) => (
        <div>
          <Switch
            checked={record.IsEnabled}
            onClick={() => handleEnableManual(record)}
          />
          <Button type="text" onClick={() => handleContent(record)}>
            内容管理
          </Button>
          <Button
            type="text"
            disabled={record.IsEnabled}
            onClick={() => handleAddOrEdit(OperateType.Edit, record)}
          >
            编辑
          </Button>
          <Popconfirm
            focusLock
            title="提示"
            content="是否确认删除？"
            disabled={record.IsEnabled}
            onOk={() => {
              deleteRow(record);
            }}
          >
            <Button type="text" status="danger" disabled={record.IsEnabled}>
              删除
            </Button>
          </Popconfirm>
        </div>
      ),
    },
  ];

  useEffect(() => {
    getData();
  }, []);

  const handleContent = (record) => {
    history.push({
      pathname: '/manuals/manualsContent',
      search: `?ID=${record.ID}`,
    });
  };

  return (
    <div>
      <Card>
        <Button
          type="primary"
          onClick={() => handleAddOrEdit(OperateType.Add)}
          style={{ marginBottom: 20 }}
        >
          新增
        </Button>
        <Table
          border
          borderCell
          scroll={{
            x: 1600,
            y: 500,
          }}
          columns={columns}
          pagination={pagination}
          data={data}
          loading={loading}
          onChange={onChangeTable}
          rowKey="ID"
        />
      </Card>

      <AddOrEditForm
        visible={modalVisible}
        editData={editData}
        modalTitle={formShowType === OperateType.Add ? '新增教程' : '编辑教程'}
        formShowType={formShowType}
        handleChangeVisible={handleChangeVisible}
        onConfirm={onConfirm}
        onCancel={onCancel}
      ></AddOrEditForm>
    </div>
  );
}

export default Manuals;
